import { getWxConfig } from "../api"
import { toast } from "./native"
// #ifdef H5
const jWeixin = require("jweixin-module")
// #endif

export const pay = (payInfo, callback) => {
	const { timeStamp, nonceStr, paySign, packageStr, order } = payInfo
	// #ifdef H5
	getWxConfig(window.location.href).then((data) => {
		console.log(data)
		const { timestamp, nonceStr: nonceStr1, signature } = data
		// 后台接口返回的配置参数
		const wxConfig = {
			debug: true,
			appId: 'wx64086f6785cd343b',
			timestamp,
			nonceStr: nonceStr1,
			signature
		}
		// 初始化微信 JS-SDK
		jWeixin.config({
			...wxConfig,
			jsApiList: ['chooseWXPay']
		})
		jWeixin.ready(function() {
			// TODO
			jWeixin.chooseWXPay({
				timestamp: timeStamp.toString(),
				nonceStr,
				package: packageStr,
				signType: 'RSA',
				paySign,
				success: function(res) {
					callback && callback()
					uni.navigateTo({
						url: `/pages/index/verification/verification?id=${order.id}`
					})
				},
				fail: function() {
					console.log('支付失败', res)
					toast('支付失败')
				}
			})
		})
	})
	// #endif

	// #ifdef MP-WEIXIN
	wx.requestPayment({
		timeStamp: timeStamp.toString(),
		nonceStr,
		package: packageStr,
		signType: 'RSA',
		paySign,
		success(res) {
			console.log(res)
			callback && callback()
			uni.navigateTo({
				url: `/pages/index/verification/verification?id=${order.id}`
			})
		},
		fail(res) {
			console.log('支付失败', res)
			toast('支付失败')
		}
	})
	// #endif
}